using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace Gj.DarkLoong
{
    /// <summary>
    /// 真正的IP路由HTTP客户端
    /// 完全不修改URL，通过Socket直接连接到指定IP
    /// </summary>
    public class TrueIpRouterClient
    {
        /// <summary>
        /// 发送HTTP请求到指定IP，完全不修改URL
        /// </summary>
        public static async Task<string> SendRequest(
            string originalUrl,
            string targetIp,
            int targetPort,
            string method = "GET",
            string data = null,
            Dictionary<string, string> headers = null)
        {
            try
            {
                // 解析原始URL
                var uri = new Uri(originalUrl);
                var originalHost = uri.Host;
                var path = uri.PathAndQuery;

                Debug.Log($"[TrueIpRouterClient] Connecting to IP: {targetIp}:{targetPort}");
                Debug.Log($"[TrueIpRouterClient] Original URL: {originalUrl}");
                Debug.Log($"[TrueIpRouterClient] Original Host: {originalHost}");
                Debug.Log($"[TrueIpRouterClient] Path: {path}");

                // 创建Socket连接
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    // 连接到指定IP
                    await socket.ConnectAsync(targetIp, targetPort);

                    Stream stream = new NetworkStream(socket, false);
                    
                    // 如果是HTTPS请求，需要SSL/TLS处理
                    if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
                    {
                        Debug.Log($"[TrueIpRouterClient] Establishing SSL/TLS connection to {originalHost}");
                        
                        var sslStream = new SslStream(stream, false, ValidateServerCertificate);
                        await sslStream.AuthenticateAsClientAsync(originalHost);
                        
                        stream = sslStream;
                        Debug.Log($"[TrueIpRouterClient] SSL/TLS connection established");
                    }

                    // 构建HTTP请求
                    var httpRequest = BuildHttpRequest(method, path, originalHost, data, headers);

                    Debug.Log($"[TrueIpRouterClient] HTTP Request:\n{httpRequest}");

                    // 发送请求
                    var requestBytes = Encoding.UTF8.GetBytes(httpRequest);
                    await stream.WriteAsync(requestBytes, 0, requestBytes.Length);

                    // 接收响应
                    var response = await ReceiveResponse(stream);

                    Debug.Log($"[TrueIpRouterClient] Response received: {response.Length} bytes");

                    // 解析响应，提取响应体
                    var responseBody = ExtractResponseBody(response);
                    return responseBody;
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[TrueIpRouterClient] Exception: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 构建HTTP请求字符串
        /// </summary>
        private static string BuildHttpRequest(
            string method,
            string path,
            string host,
            string data,
            Dictionary<string, string> headers)
        {
            var request = new StringBuilder();

            // 请求行
            request.AppendLine($"{method} {path} HTTP/1.1");

            // Host头
            request.AppendLine($"Host: {host}");

            // 添加自定义头部
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AppendLine($"{header.Key}: {header.Value}");
                }
            }

            // 内容长度
            if (!string.IsNullOrEmpty(data))
            {
                var dataBytes = Encoding.UTF8.GetBytes(data);
                request.AppendLine($"Content-Length: {dataBytes.Length}");
                request.AppendLine("Content-Type: application/json");
            }

            // 连接头
            request.AppendLine("Connection: close");

            // 空行
            request.AppendLine();

            // 请求体
            if (!string.IsNullOrEmpty(data))
            {
                request.Append(data);
            }

            return request.ToString();
        }

        /// <summary>
        /// 接收HTTP响应
        /// </summary>
        private static async Task<string> ReceiveResponse(Stream stream)
        {
            var buffer = new byte[4096];
            var response = new StringBuilder();

            while (true)
            {
                var bytesReceived = await stream.ReadAsync(buffer, 0, buffer.Length);

                if (bytesReceived == 0)
                    break;

                var chunk = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
                response.Append(chunk);

                // 检查是否接收完整
                if (IsResponseComplete(response.ToString()))
                    break;
            }

            return response.ToString();
        }

        /// <summary>
        /// 检查响应是否完整
        /// </summary>
        private static bool IsResponseComplete(string response)
        {
            // 简单的完整性检查
            return response.Contains("\r\n\r\n") && response.Length > 100;
        }

        /// <summary>
        /// 解析HTTP响应，提取响应体
        /// </summary>
        public static string ExtractResponseBody(string httpResponse)
        {
            try
            {
                var parts = httpResponse.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.None);
                if (parts.Length >= 2)
                {
                    return parts[1];
                }
                return httpResponse;
            }
            catch
            {
                return httpResponse;
            }
        }

        /// <summary>
        /// 发送JSON请求
        /// </summary>
        public static async Task<string> SendJsonRequest(
            string originalUrl,
            string targetIp,
            int targetPort,
            string method = "POST",
            object data = null,
            Dictionary<string, string> headers = null)
        {
            string jsonData = null;
            if (data != null)
            {
                jsonData = JsonUtility.ToJson(data);
            }

            var requestHeaders = headers ?? new Dictionary<string, string>();
            requestHeaders["Content-Type"] = "application/json";

            return await SendRequest(originalUrl, targetIp, targetPort, method, jsonData, requestHeaders);
        }

        /// <summary>
        /// SSL证书验证回调 - 接受所有证书（用于开发环境）
        /// 在生产环境中应该实现更严格的证书验证
        /// </summary>
        private static bool ValidateServerCertificate(
            object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            // 记录证书验证信息
            Debug.Log($"[TrueIpRouterClient] Certificate validation: {sslPolicyErrors}");
            
            // 在开发环境中，接受所有证书
            // 在生产环境中，应该检查 sslPolicyErrors 并只接受有效的证书
            return true;
        }
    }
}

